﻿using LaserAutoTest.Application;
using LaserAutoTest.Application.Models;
using LaserAutoTest.Application.Models.Mains;
using LaserAutoTest.Application.Models.PortModels;
using LaserAutoTest.Common;
using LaserAutoTest.Common.RabbitMqs;
using LaserAutoTest.Module;
using LaserAutoTest.UI.Views.Logins;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.Logging;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Net;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Controls;
using System.Windows.Threading;

namespace LaserAutoTest.UI.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly ILogger _logger;
        private readonly ITcpService _tcpService;
        private DispatcherTimer commandTimer = new DispatcherTimer();
        //private readonly IModel channel = Channels.Channel;
        public MainWindowViewModel(IRegionManager regionManager, ILogger logger, ITcpService tcpService)
        {
            _regionManager = regionManager;
            _logger = logger;
            _tcpService = tcpService;

            UserLoginCommand = new DelegateCommand<object>(ShowLogin);
            ShowRegionCommand = new DelegateCommand<object>(ShowRegion);
            Init();
        }

        #region binding

        private UserModel _user;
        public UserModel User
        {
            get { return _user; }
            set
            {
                SetProperty(ref _user, value);
            }
        }

        private ObservableCollection<MenuModel> _menuList;
        public ObservableCollection<MenuModel> MenuList
        {
            get { return _menuList; }
            set
            {
                SetProperty(ref _menuList, value);
            }
        }

        #region command
        public DelegateCommand<object> UserLoginCommand { get; set; }
        public DelegateCommand<object> ShowRegionCommand { get; set; }
        private void ShowLogin(object o)
        {
            if (GlobalValues.UserInfo != null)
                User = GlobalValues.UserInfo;
            if (User.JobNumber == "未登录")
            {
                LoginView login = new LoginView();

                login.ShowDialog();
                if (GlobalValues.UserInfo != null)
                    User = GlobalValues.UserInfo;
            }
            else
            {
                var result = GlobalValues.MessageBoxShow("是否登出当前用户？");

                if (!result)
                {
                    return;
                }
                else
                {
                    User.JobNumber = "未登录";
                    GlobalValues.UserInfo = null;
                }
            }
        }

        private void ShowRegion(object o)
        {
            var text = (o as TextBlock).Text;
            if (!string.IsNullOrEmpty(text))
                _regionManager.RequestNavigate("ContentRegion", text);
        }
        #endregion

        #endregion

        #region mq

        //private void Consume1()
        //{
        //    var queueName = "q1";
        //    RabbitClient.BindingQueue(queueName);
        //    var consumer = new EventingBasicConsumer(channel);
        //    consumer.Received += Consumer_Received;
        //    channel.BasicConsume(queueName, false, consumer);
        //}

        //private void Consumer_Received(object sender, BasicDeliverEventArgs e)
        //{
        //    var message = Encoding.UTF8.GetString(e.Body.ToArray());
        //    _logger.LogInformation($"队列1接收消息:{message}");
        //    channel.BasicAck(e.DeliveryTag, true);
        //}

        #endregion

        #region private

        private void Init()
        {
            InitUserInfo();

            InitPorts();

            StartServer();

            InitTimer();

            InitMenus();
        }

        private void InitMenus()
        {
            MenuList = new ObservableCollection<MenuModel>();
            MenuList.Add(new MenuModel()
            {
                Name = "主页",
                Icon = PackIconKind.Home,
                RegionName = "ContentView"
            });
            MenuList.Add(new MenuModel()
            {
                Name = "测试",
                Icon = PackIconKind.CovidTest,
                RegionName = "TestView",
                Children = new ObservableCollection<MenuModel> { new MenuModel() { Name = "实验", Icon = PackIconKind.Latest, RegionName = "TestView" } }
            });
            MenuList.Add(new MenuModel()
            {
                Name = "搜索",
                Icon = PackIconKind.Search,
                RegionName = "BaiduView",
                Children = new ObservableCollection<MenuModel> { new MenuModel() { Name = "百度", Icon = PackIconKind.SearchGlobe, RegionName = "BaiduView" } }
            });
            MenuList.Add(new MenuModel()
            {
                Name = "设置",
                Icon = PackIconKind.Settings,
                RegionName = "SettingView",
                Children = new ObservableCollection<MenuModel> { new MenuModel() { Name = "个人账户", Icon = PackIconKind.AccountSettings, RegionName = "SettingView" } }
            });
        }

        private void InitUserInfo()
        {
            if (GlobalValues.UserInfo != null)
                User = GlobalValues.UserInfo;
            else
                User = new UserModel() { JobNumber = "未登录" };
        }

        private void InitPorts()
        {
            GlobalValues.Ports.Clear();
            GlobalValues.Ports.TryAdd("192.168.29.101:4104", new PortModel()
            {
                IpAddress = "192.168.29.101:4104",
                Command = new System.Collections.Generic.List<CommandModel>
                {
                    new CommandModel()
                    {
                        CommandName ="RSN",
                        DestinationIP = "192.168.29.101:4104".ToIPEndPoint()
                    }
                }
            });
        }

        private void StartServer()
        {
            GlobalValues.TcpServer = new SocketTcpServer();
            GlobalValues.TcpServer.pushSockets = new PushSockets(_tcpService.ReceiveData);
            GlobalValues.TcpServer.InitSocket(IPAddress.Any, 4196);
            GlobalValues.TcpServer.Start();
        }


        private void InitTimer()
        {
            commandTimer.Interval = TimeSpan.FromMilliseconds(10);
            commandTimer.Tick += async (sender, e) =>
            {
                await Task.Run(async () =>
                {
                    await CommandTimer_Tick(sender, e);
                });
            };
            commandTimer.Start();
        }

        private async Task CommandTimer_Tick(object sender, EventArgs e)
        {
            commandTimer.Stop();
            await _tcpService.SendData();
            commandTimer.Start();
        }

        #endregion
    }
}
